import express from 'express'
import expressWs from 'express-ws'
import bodyParser from 'body-parser'

import { findReqHandler, getPathVariables, wsMap } from './requestManager.js'

import './src/api.js'

const app = express()
expressWs(app)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

for (const [k, v] of wsMap) {
  /** @type {import('express-ws').WithWebsocketMethod} */ /** @type {unknown} */ app.ws(k, v)
}

app.use('/', function (req, res, next) {
  const path = req.path.replace(/\\/g, '/')
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', '*')
  res.header('Access-Control-Allow-Methods', '*')
  console.log(path, req.path, req.method)
  const handler = findReqHandler({ method: req.method, path })
  if (!handler) {
    if (req.method === 'OPTIONS') {
      res.statusCode = 200
      res.end()
    } else {
      res.statusCode = 404
      res.end()
    }
  } else {
    const [{ path: pattern }, fn] = handler
    const pathVars = getPathVariables(path, pattern)
    const result = fn({ query: req.query, body: req.body, pathVars })
    res.end(JSON.stringify(result))
  }
})

app.listen(3129, () => {
  console.log('server side: http://localhost:3129')
})
